import type { UserStatus } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import moment from 'moment';

import 'highlight.js/styles/github.css';
import { sdk } from '../../app/utils/client/lib/SDKClient';
import { synchronizeUserData, removeLocalUserData } from '../lib/userData';
import { fireGlobalEvent } from '../lib/utils/fireGlobalEvent';
import { watchUserId } from '../meteor/user';

Meteor.startup(() => {
	let status: UserStatus | undefined = undefined;
	Tracker.autorun(async () => {
		const uid = watchUserId();
		if (!uid) {
			removeLocalUserData();
			return;
		}

		if (!Meteor.status().connected) {
			return;
		}

		if (Meteor.loggingIn()) {
			return;
		}

		const user = await synchronizeUserData(uid);
		if (!user) {
			return;
		}

		const utcOffset = moment().utcOffset() / 60;
		if (user.utcOffset !== utcOffset) {
			sdk.call('userSetUtcOffset', utcOffset);
		}

		if (user.status !== status) {
			status = user.status;
			fireGlobalEvent('status-changed', status);
		}
	});
});
